import React, { ReactNode, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { useRealtime } from '../hooks/useRealtime';

interface LayoutProps {
  children: ReactNode;
}

const Layout: React.FC<LayoutProps> = ({ children }) => {
  const { user, logout } = useAuth();
  const { isConnected } = useRealtime();
  const location = useLocation();
  const navigate = useNavigate();
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [isCollapsed, setIsCollapsed] = useState(false);

  const navigation = [
    {
      name: '数据概览',
      href: '/dashboard',
      icon: 'fas fa-chart-pie',
      current: location.pathname === '/dashboard',
    },
    {
      name: '工单管理',
      href: '/orders',
      icon: 'fas fa-list-alt',
      current: location.pathname.startsWith('/orders'),
    },
    {
      name: '维修员管理',
      href: '/maintainers',
      icon: 'fas fa-users',
      current: location.pathname === '/maintainers',
    },
    {
      name: '统计分析',
      href: '/statistics',
      icon: 'fas fa-chart-line',
      current: location.pathname === '/statistics',
    },
  ];

  const handleLogout = async () => {
    try {
      await logout();
      navigate('/login');
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  const getPageTitle = () => {
    const current = navigation.find(item => item.current);
    return current?.name || '工单管理系统';
  };

  return (
    <div className="min-h-screen bg-admin-bg">
      {/* 侧边栏 */}
      <div
        className={`fixed inset-y-0 left-0 z-50 bg-admin-sidebar transform transition-all duration-300 ease-in-out ${
          isSidebarOpen ? 'translate-x-0' : '-translate-x-full'
        } lg:translate-x-0 ${
          isCollapsed ? 'w-16' : 'w-64'
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Logo */}
          <div className="flex items-center justify-between p-6 border-b border-slate-700">
            <div className="flex items-center">
              <i className="fas fa-tools text-2xl text-white mr-3"></i>
              {!isCollapsed && <h1 className="text-xl font-bold text-white">综合管理平台</h1>}
            </div>
            <div className="flex items-center space-x-2">
              {/* 折叠按钮 - 桌面端 */}
              <button
                onClick={() => setIsCollapsed(!isCollapsed)}
                className="hidden lg:block text-gray-400 hover:text-white transition-colors duration-200"
                title={isCollapsed ? '展开菜单' : '收起菜单'}
              >
                <i className={`fas ${isCollapsed ? 'fa-chevron-right' : 'fa-chevron-left'}`}></i>
              </button>
              {/* 关闭按钮 - 移动端 */}
              <button
                onClick={() => setIsSidebarOpen(false)}
                className="lg:hidden text-gray-400 hover:text-white"
              >
                <i className="fas fa-times"></i>
              </button>
            </div>
          </div>

          {/* 导航菜单 */}
          <nav className="flex-1 px-4 py-6 space-y-2">
            {navigation.map((item) => (
              <div key={item.name} className="relative group">
                <Link
                  to={item.href}
                  className={`flex items-center px-4 py-3 text-sm font-medium rounded-lg transition-colors duration-200 ${
                    item.current
                      ? 'bg-admin-primary text-white'
                      : 'text-gray-300 hover:bg-slate-700 hover:text-white'
                  } ${isCollapsed ? 'justify-center' : ''}`}
                  title={isCollapsed ? item.name : ''}
                >
                  <i className={`${item.icon} text-lg ${isCollapsed ? '' : 'mr-3'}`}></i>
                  {!isCollapsed && <span>{item.name}</span>}
                </Link>
                
                {/* 收起时的提示气泡 */}
                {isCollapsed && (
                  <div className="absolute left-full top-1/2 transform -translate-y-1/2 ml-3 px-2 py-1 bg-gray-900 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                    {item.name}
                    <div className="absolute right-full top-1/2 transform -translate-y-1/2 border-4 border-transparent border-r-gray-900"></div>
                  </div>
                )}
              </div>
            ))}
          </nav>

          {/* 用户信息和连接状态 */}
          <div className="p-4 border-t border-slate-700">
            {isCollapsed ? (
              <div className="flex flex-col items-center space-y-3">
                {/* 连接状态指示器 */}
                <div className="relative group">
                  <div
                    className={`w-3 h-3 rounded-full ${
                      isConnected ? 'bg-green-500' : 'bg-red-500'
                    }`}
                  ></div>
                  {/* 连接状态提示气泡 */}
                  <div className="absolute left-full top-1/2 transform -translate-y-1/2 ml-3 px-2 py-1 bg-gray-900 text-white text-xs rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                    {isConnected ? '实时连接' : '连接断开'}
                    <div className="absolute right-full top-1/2 transform -translate-y-1/2 border-4 border-transparent border-r-gray-900"></div>
                  </div>
                </div>
                {/* 用户头像 */}
                <div className="relative group">
                  <i className="fas fa-user-circle text-2xl text-gray-300"></i>
                  {/* 用户信息提示气泡 */}
                  <div className="absolute left-full top-1/2 transform -translate-y-1/2 ml-3 px-2 py-1 bg-gray-900 text-white text-xs rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                    {user?.name}
                    <div className="absolute right-full top-1/2 transform -translate-y-1/2 border-4 border-transparent border-r-gray-900"></div>
                  </div>
                </div>
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center">
                    <div
                      className={`w-2 h-2 rounded-full mr-2 ${
                        isConnected ? 'bg-green-500' : 'bg-red-500'
                      }`}
                    ></div>
                    <span className="text-xs text-gray-400">
                      {isConnected ? '实时连接' : '连接断开'}
                    </span>
                  </div>
                </div>
                <div className="flex items-center text-sm text-gray-300">
                  <i className="fas fa-user-circle text-lg mr-2"></i>
                  <span>{user?.name}</span>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className={`transition-all duration-300 ease-in-out flex flex-col min-h-screen ${
        isCollapsed ? 'lg:ml-16' : 'lg:ml-64'
      }`}>
        {/* 顶部导航栏 */}
        <header className="bg-white shadow-sm border-b border-gray-200">
          <div className="flex items-center justify-between px-6 py-4">
            <div className="flex items-center">
              <button
                onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                className="lg:hidden mr-4 text-gray-500 hover:text-gray-700"
              >
                <i className="fas fa-bars text-lg"></i>
              </button>
              {/* 桌面端展开按钮（当侧边栏收起时） */}
              {isCollapsed && (
                <button
                  onClick={() => setIsCollapsed(false)}
                  className="hidden lg:block mr-4 text-gray-500 hover:text-gray-700"
                  title="展开菜单"
                >
                  <i className="fas fa-bars text-lg"></i>
                </button>
              )}
              <h1 className="text-2xl font-semibold text-gray-900">{getPageTitle()}</h1>
            </div>

            <div className="flex items-center space-x-4">
              {/* 刷新按钮 */}
              <button
                onClick={() => window.location.reload()}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200"
                title="刷新页面"
              >
                <i className="fas fa-sync-alt"></i>
              </button>

              {/* 通知图标 */}
              <div className="relative">
                <button className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                  <i className="fas fa-bell"></i>
                  {/* 通知徽章 */}
                  <span className="absolute -top-1 -right-1 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-500 rounded-full">
                    3
                  </span>
                </button>
              </div>

              {/* 用户菜单 */}
              <div className="relative group">
                <button className="flex items-center p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                  <i className="fas fa-user-circle text-lg mr-2"></i>
                  <span className="text-sm font-medium">{user?.name}</span>
                  <i className="fas fa-chevron-down ml-2 text-xs"></i>
                </button>
                
                {/* 下拉菜单 */}
                <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50">
                  <div className="py-2">
                    <button
                      onClick={handleLogout}
                      className="flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-200"
                    >
                      <i className="fas fa-sign-out-alt mr-3"></i>
                      退出登录
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </header>

        {/* 页面内容 */}
        <main className="flex-1 p-6 w-full">
          <div className="h-full w-full">
            {children}
          </div>
        </main>
      </div>

      {/* 移动端遮罩 */}
      {isSidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black bg-opacity-50 lg:hidden"
          onClick={() => setIsSidebarOpen(false)}
        ></div>
      )}
    </div>
  );
};

export default Layout;